package main

import (
	"embed"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

func managerHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to WebSocket <=> TCP Proxy")
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		// 解决跨域问题
		return true
	},
}

// 本示例提供 websocket 回显测试功能
func wsktEchoHandler(w http.ResponseWriter, r *http.Request) {
	// 升级当前 HTTP 连接为 WebSocket 连接
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("Upgrade failed:", err)
		return
	}

	// Use conn to send and receive messages.
	go func() {
		log.Printf("%s => %s", r.URL, conn.RemoteAddr())

		for {
			messageType, payload, err := conn.ReadMessage()
			if err != nil {
				log.Println(err)
				break
			}

			if err := conn.WriteMessage(messageType, payload); err != nil {
				log.Println(err)
				break
			}
		}

		log.Println("WebSocket disconnected: ", conn.RemoteAddr())
		conn.Close()
	}()
}

// 内置 Web 页面
//go:embed *.md *.html static/*
var webroot embed.FS

func main() {
	// 设置日志格式
	log.SetFlags(log.LstdFlags | log.Lshortfile)

	// 设置 URL 处理函数
	mux := http.NewServeMux()
	mux.HandleFunc("/manager", managerHandler)
	mux.HandleFunc("/wskt/echo", wsktEchoHandler)
	mux.HandleFunc("/wskt/tcp", wsktTcpHandler)
	mux.HandleFunc("/wskt/serial", wsktSerialHandler)
	mux.Handle("/", http.FileServer(http.FS(webroot)))

	// 监听请求端口
	log.Println("Listening on 8000 ...")
	log.Println("Access the inner test for help:\r\n\thttp://localhost:8000")
	err := http.ListenAndServe(":8000", mux)
	if err != nil {
		log.Println(err)
	}
}
